package com.tkjt.pms.calc.formula.excel.builder.impl;

import java.util.List;

import org.springframework.stereotype.Component;

import com.tkjt.pms.calc.formula.common.FormulaConsts;
import com.tkjt.pms.calc.formula.common.FormulaVariableCells;
import com.tkjt.pms.calc.formula.excel.builder.DataKeyBuilder;
import com.tkjt.pms.calc.utils.EsCalcUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component(FormulaConsts.F_DATA_KEY_QS)
public class DataKeyQsBuilder implements DataKeyBuilder {

	@Override
	public FormulaVariableCells doBuilder(String formula, String variable, List<Double> variableValue, int lineNumber, String dataColumn, String indexYearMonth) {

		FormulaVariableCells formulaVariableCells = new FormulaVariableCells();
		
		StringBuilder excelFormulaBuilder = new StringBuilder(formula);
		
		Integer calcQi = EsCalcUtils.getDataColumnQi(dataColumn);
		char startCol = 'N';
		String extendCellKey = "(";
		for (int index = 1; index <= 4; index++) {
			String cellKey = String.valueOf(startCol) + lineNumber;
			if (index > calcQi) {
				formulaVariableCells.addCellValue(cellKey, null);
			} else {
				Double oneCellColumnValue = variableValue.get(12+index);
				if(null == oneCellColumnValue) {
					formulaVariableCells.addCellValue(cellKey, null);
				} else {
					formulaVariableCells.addCellValue(cellKey, oneCellColumnValue.toString());
				}
				if (oneCellColumnValue < 0) {
					cellKey = "(" + cellKey + ")";
				}
				extendCellKey += cellKey;
				extendCellKey += "+";
			}
			startCol += 1;
		}
		if (extendCellKey.charAt(extendCellKey.length() - 1) == '+') {
			extendCellKey = extendCellKey.substring(0, extendCellKey.length() - 1);
			extendCellKey += ")";
		}
		int start = 0;
		while(true) {
			int index = excelFormulaBuilder.indexOf(variable, start);
			if(index<0) {
				break;
			}
			if(index == 0){
				excelFormulaBuilder.replace(index, index+variable.length(), extendCellKey);
			}
			if(index > 0 && !EsCalcUtils.isVariableChar(excelFormulaBuilder.charAt(index-1))){
				excelFormulaBuilder.replace(index, index+variable.length(), extendCellKey);
			}
			start++;
		}
		
		formulaVariableCells.setCellFormula(excelFormulaBuilder.toString());
		
		log.debug(formulaVariableCells.getCellFormula());

		return formulaVariableCells;
	}

}
